package com.shuqi.model;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.shuqi.activity.BookContentActivity;
import com.shuqi.activity.adapter.ShareDialogAdapter;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.utils.AboutShareConst;
import com.shuqi.controller.R;
import com.shuqi.model.bean.BookContentInfo;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SnsPostListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.db.OauthHelper;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.media.CircleShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.WeiXinShareContent;
import com.umeng.socialize.sso.TencentWBSsoHandler;
import com.umeng.socialize.sso.UMWXHandler;

/**
 * 分享功能
 * @author GaoPeng
 *
 */
public class ShareModel {

    private Context mContext;
    private LayoutInflater layoutInflater;
    private Dialog dialogHead;
    public final UMSocialService mController = UMServiceFactory.getUMSocialService(
            "com.umeng.share", RequestType.SOCIAL);
    private int share_position=-1;
    private GridView gridview;
    private Button mShareCancelButton;
    private View share_shuqi_dialog;
    private String shareTitle;
    String shareText;
    private boolean isScreenVertical=true;
    
    /**
     * 构造函数
     * @param context
     */
    public ShareModel(Context context) {
        this.mContext=context;
        layoutInflater = LayoutInflater.from(this.mContext);
        share_shuqi_dialog =
                (LinearLayout) layoutInflater.inflate(R.layout.share_shuqi_dialog, null);
        gridview = (GridView) share_shuqi_dialog.findViewById(R.id.share_dialog);
        mShareCancelButton = (Button) share_shuqi_dialog.findViewById(R.id.share_dialog_cancel);
        
        dialogHead = new Dialog(context, R.style.MyDialogTransparent);
        dialogHead.setCanceledOnTouchOutside(true);
        dialogHead.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialogHead.setContentView(share_shuqi_dialog);
        dialogHead.setCanceledOnTouchOutside(true);
    }
    
    /**
     * 调用分享功能
     * @param content
     * @param title
     * @param url
     * @param img
     * @param mBookContentInfo
     */
    public void share(String content,String title,String url,String img,BookContentInfo mBookContentInfo) {
        if (TextUtils.isEmpty(content)) {
            ((BookContentActivity) mContext).showMsg("分享内容为空");
        } else {
            
            // 正文页分享模式下判断横竖屏
            if(mBookContentInfo!=null) {
                isScreenVertical = BookContentSettings.getInstance(mContext).getVertialScreen();
            }
            
            // 弹出分享对话框
            openShareDialog();
            
            String mContent="";
            String mContent2="";
            String mTitle="";
            UMImage shareImage=null;
            UMImage shareImage2=null;
            
            if(mBookContentInfo!=null) {
                
                // 分享标题
                mTitle = mBookContentInfo.getBookname();
                // 分享图片
                Bitmap bookCover = getBookCover(mBookContentInfo.getImageUrl());
                shareImage2 = new UMImage(mContext, bookCover);
                shareImage =
                        new UMImage(mContext, getSharePicture(
                                mContext,
                                content,
                                mBookContentInfo.getBookname(),
                                mBookContentInfo.getAuthor(),
                                ((BookContentActivity) mContext).getResources().getString(
                                        R.string.app_name), bookCover));
                // 根据文字长度格式化文字
                mContent = parseStrByLen(content, 100, "...");
                // 根据书籍类型设置不同分享内容
                switch (mBookContentInfo.getType()) {
                    case 1:// 收费
                        mContent2 =
                                "#书旗小说#“" + mContent + "”——《" + mBookContentInfo.getBookname()
                                        + "》@书旗小说官博";
                        break;
                    case 2:// 神马
                        mContent2 =
                                "#神马小说都能搜#“" + mContent + "”——《"
                                        + mBookContentInfo.getBookname() + "》@书旗小说官博";
                        break;
                    default:// 本地
                        mContent2 =
                                "#小说阅读神器#“" + mContent + "”——《" + mBookContentInfo.getBookname()
                                        + "》@书旗小说官博";
                        break;
                }
            } else {
                mContent=mContent2="#书旗小说#"+content+" 赶快来关注@书旗小说官博";
                mTitle=title;
                if (!TextUtils.isEmpty(img)) {
                    shareImage = shareImage2 = new UMImage(mContext, img);
                }
            }

            // 设置微信标题
            UMWXHandler wxHandler =
                    mController.getConfig().supportWXPlatform(mContext,
                            AboutShareConst.appID, url);
            wxHandler.setWXTitle(mTitle);
            // 设置微信朋友圈标题
            UMWXHandler circleHandler =
                    mController.getConfig().supportWXCirclePlatform(mContext,
                            AboutShareConst.appID, url);
            circleHandler.setCircleTitle(mTitle);

            mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
            // mController.getConfig().setSsoHandler(new SinaSsoHandler());

            mController.setShareContent(mContent2);
            
            if(mBookContentInfo!=null) {
                // 只有自有书籍才生成图片
                if (mBookContentInfo.getType() == 1 || mBookContentInfo.getType() == 2) {
                    mController.setShareMedia(shareImage);
                }
            } else {
                mController.setShareMedia(shareImage);
            }
            
            // 微信朋友圈把封面页当图片
            WeiXinShareContent weixinContent = new WeiXinShareContent(shareImage2);
            weixinContent.setShareContent(mContent);
            mController.setShareMedia(weixinContent);
            CircleShareContent circleContent = new CircleShareContent(shareImage2);
            circleContent.setShareContent(mContent);
            mController.setShareMedia(circleContent);

            showSharePlat(mTitle, mContent2);
        }
    }
    
    /**
     * 判断是否安装了微信
     * @param context
     * @param api
     * @return
     */
    private boolean isWXAppInstalledAndSupported(Context context, IWXAPI api) {
        Boolean isInstallWX = api.isWXAppInstalled() && api.isWXAppSupportAPI();
        return isInstallWX;
    }

    /**
     * 发送分享
     * @param plat
     */
    private void sendShare(final SHARE_MEDIA plat) {
        
        // 关闭toast消息提示
        mController.getConfig().closeToast();
        
        final SnsPostListener listener = new SnsPostListener() {
            @Override
            public void onStart() {
                //Toast.makeText(mContext, "正在分享", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(SHARE_MEDIA platform, int eCode, SocializeEntity entity) {
                if (eCode == 200) {
                    Toast.makeText(mContext, "分享成功", Toast.LENGTH_SHORT).show();
                } else {
                    /*
                     * String eMsg = ""; if (eCode == -101) { eMsg = "没有授权"; }
                     */
                    Toast.makeText(mContext, "分享失败", Toast.LENGTH_SHORT).show();
                }
            }

        };

        if (!OauthHelper.isAuthenticated(mContext, plat)
                && plat != SHARE_MEDIA.WEIXIN && plat != SHARE_MEDIA.WEIXIN_CIRCLE) {
            mController.doOauthVerify(mContext, plat, new UMAuthListener() {
                @Override
                public void onStart(SHARE_MEDIA platform) {
                    //Toast.makeText(mContext, "授权开始", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(SocializeException e, SHARE_MEDIA platform) {
                    //Toast.makeText(mContext, "授权错误", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onComplete(Bundle value, SHARE_MEDIA platform) {
                    //Toast.makeText(mContext, "授权完成", Toast.LENGTH_SHORT).show();
                    mController.postShare(mContext, plat, listener);
                }

                @Override
                public void onCancel(SHARE_MEDIA platform) {
                    //Toast.makeText(mContext, "授权取消", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            mController.postShare(mContext, plat, listener);
        }
    }

    /**
     * 打开分享面板
     * @param shareTitle
     * @param shareText
     */
    private void showSharePlat(String shareTitle, String shareText) {
        Window dialogWindow = dialogHead.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = android.view.ViewGroup.LayoutParams.FILL_PARENT;
        lp.gravity = Gravity.BOTTOM;
        lp.windowAnimations = R.style.PopupAnimation;
        dialogWindow.setAttributes(lp);
        this.shareTitle = shareTitle;
        this.shareText = shareText;
        dialogHead.show();
    }

    /**
     * 处理分享
     */
    private void doShare() {
        if(share_position>=0) {
            if (share_position == gridview.getAdapter().getCount() - 1) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, shareTitle);
                intent.putExtra(Intent.EXTRA_TEXT, shareText);
                mContext.startActivity(Intent.createChooser(intent,"请选择程序"));
                dialogHead.hide();
            } else {
                sendShare(((ShareDialogAdapter.ShareEntity)gridview.getAdapter().getItem(share_position)).getMedia());
            }
        }
    }
    
    /**
     * 弹出分享对话框
     */
    private void openShareDialog() {
        final ShareDialogAdapter adapter =
                new ShareDialogAdapter(mContext, isWXAppInstalledAndSupported(mContext,
                        WXAPIFactory.createWXAPI(mContext, AboutShareConst.appID)));
        gridview.setAdapter(adapter);
        // 移除点击背景效果
        gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        // 横竖屏显示不同列数
        if (isScreenVertical) {
            gridview.setNumColumns(4);
        } else {
            gridview.setNumColumns(5);
        }
        // 添加消息处理
        gridview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                dialogHead.hide();
                share_position=position;
                doShare();
            }
        });
        // 绑定分享弹出框取消按钮事件
        mShareCancelButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialogHead.hide();
            }

        });
    }
    
    /**
     * 获取书籍封面图
     * @param bookCover
     * @return
     */
    private Bitmap getBookCover(String bookCover) {
        Bitmap bitmap = null;
        if(bookCover!=null) {
            bitmap = BitmapFactory.decodeFile(com.shuqi.common.Config.BOOK_COVER_BIG_CACHE_PATH+bookCover.hashCode());
            if(bitmap==null) {
                bitmap = BitmapFactory.decodeFile(com.shuqi.common.Config.BOOK_COVER_SMALL_CACHE_PATH+bookCover.hashCode());
            }
        }
        if(bitmap==null) {
            bitmap=BitmapFactory.decodeResource(ShuqiApplication.getContext().getResources(), R.drawable.share_cover, null);
        }
        return bitmap;
    }
    
    /**
     * 获取分享图片
     * @param context
     * @param content
     * @param bookName
     * @param bookAuthor
     * @param copyright
     * @param bookCover
     * @return
     */
    private Bitmap getSharePicture(Context context,String content,String bookName,String bookAuthor,String copyright,Bitmap bookCover) {
        LayoutInflater factory = LayoutInflater.from(context);
        View view = factory.inflate(R.layout.view_share_picture, null);
        ((TextView) view.findViewById(R.id.share_txt_content)).setText("“"+content+"”");
        ((TextView) view.findViewById(R.id.share_text_bookname)).setText(bookName);
        ((TextView) view.findViewById(R.id.share_text_author)).setText(bookAuthor);
        ((TextView) view.findViewById(R.id.share_text_copyright)).setText("来自"+copyright+"客户端");
        
        ImageView image = (ImageView) view.findViewById(R.id.share_img_bookcover);
        if(bookCover!=null) {
            image.setImageBitmap(bookCover);
        }
        
        view.setDrawingCacheEnabled(true);
        view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        return view.getDrawingCache();
    }
    
    /**
     * 根据文字长度格式化字符串
     * @param str
     * @param length
     * @param dem
     * @return
     */
    private static String parseStrByLen(String str, int length, String dem) {
        if (str != null && !str.equalsIgnoreCase("")) {
            if (str.length() > length) {
                return str.substring(0, length) + dem;
            }
        }
        return str;
    }
}
